package com.kly.smartbi.bizmq;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.kly.smartbi.common.ErrorCode;
import com.kly.smartbi.exception.ThrowUtils;
import com.kly.smartbi.manager.QwenManager;
import com.kly.smartbi.model.dto.chart.ChartAddRequest;
import com.kly.smartbi.model.entity.Chart;
import com.kly.smartbi.model.entity.ChartResult;
import com.kly.smartbi.model.enums.ChartStatusEnum;
import com.kly.smartbi.service.ChartService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

import static com.kly.smartbi.constant.CommonConstant.*;

/**
 * @author admin
 * @date 2025/4/3
 */
@Configuration
public class GenChartMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private QwenManager qwenManager;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQ_CHART_QUEUE, durable = "true"),
            exchange = @Exchange(value = MQ_CHART_EXCHANGE, delayed = "true"),
            key = {MQ_CHART_ROUTING_KEY}
    ))
    public void receiveMessage(Long chartId) {
        System.out.println("receive message: " + chartId);
        //     获取待处理任务
        Chart chartDb = chartService.getById(chartId);
        ThrowUtils.throwIf(chartDb == null, ErrorCode.NOT_FOUND_ERROR, "图表不存在");
        String chartData = chartDb.getChartData();
        ChartAddRequest chartAddRequest = BeanUtil.copyProperties(chartDb, ChartAddRequest.class);
        // 异步执行
        ChartResult chartResult = qwenManager.genChartByQwen(chartAddRequest, chartData);
        ThrowUtils.throwIf(chartResult == null, ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        String genChart = chartResult.getOption();
        String genResult = chartResult.getGenResult();
        ThrowUtils.throwIf(StrUtil.hasBlank(genChart, genResult), ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        // 保存生成结果到数据库
        Chart chart = BeanUtil.copyProperties(chartDb, Chart.class);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setStatus(ChartStatusEnum.SUCCESS.getCode());
        chart.setExecMessage("AI 任务执行成功");
        boolean update = chartService.lambdaUpdate()
                .eq(Chart::getId, chart.getId())
                .eq(Chart::getUserId, chart.getUserId())
                .update(chart);
        ThrowUtils.throwIf(!update, ErrorCode.SYSTEM_ERROR, "保存失败");
    }
}
